// ChSClientContext.cpp : implementation file
//

#include "stdafx.h"
#include "ChatServer.h"
#include "ChSClientContext.h"


// CChSClientContext

CChSClientContext::CChSClientContext()
{
	m_strUserName = _T("unknown");
	m_bFirstMessage = TRUE;
}

CChSClientContext::~CChSClientContext()
{
	m_strUserName.FreeExtra();
}

void CChSClientContext::OnReceive(int nErrorCode)
{
	TCHAR buff[4096];
	int nRead;
	nRead = Receive(buff, 4096); 

	switch (nRead)
	{
	case 0:
		Close();
		break;
	case SOCKET_ERROR:
		if (GetLastError() != WSAEWOULDBLOCK) 
		{
			AfxMessageBox (_T("Error occurred"));
			Close();
		}
		break;
	default:
		buff[nRead] = _T('\0'); //terminate the string
		CString szTemp(buff);
		if (szTemp.CompareNoCase(_T("bye")) == 0)
		{
			ShutDown();
			Close();
			AfxGetApp()->GetMainWnd()->PostMessage(CHSM_CLIENT_DISCONNECT,0,(LPARAM)this);
			return;
		}

		if(TRUE == m_bFirstMessage)
		{
			if(TRUE == CChSServer::Instance()->FindClient(buff))
			{
				UserName(buff);
				CString strMsg = _T("badlogin");
				Send((LPCTSTR)strMsg,(strMsg.GetLength()+1)*sizeof(TCHAR));
				ShutDown();
				Close();
				AfxGetApp()->GetMainWnd()->PostMessage(CHSM_CLIENT_NAME_DUPLICATE,0,(LPARAM)this);
			}
			else
			{
				UserName(buff);
				AfxGetApp()->GetMainWnd()->SendMessage(CHSM_RECEIVE_CLIENT_NAME,0,(LPARAM)buff);
				CChSServer::Instance()->SendToClientUsersList(this);
			}
			
			m_bFirstMessage = FALSE;
		}
		else
		{
			CChSLogWriter::Instance()->WriteLog(buff);
			CChSServer::Instance()->SendToAll(buff);
		}		
	}
	CAsyncSocket::OnReceive(nErrorCode);

}
// CChSClientContext member functions
